<template>
  <el-tag
    :type="tagType"
    :size="size"
    :class="customClass"
    :effect="effect"
    :round="round"
    :closable="closable"
    @close="handleClose"
  >{{ displayText }}</el-tag>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { useDictStore } from "@/stores/dict";

const props = defineProps({
  // 字典类型编码
  dictType: {
    type: String,
    required: true,
  },
  // 当前状态值
  value: {
    type: [String, Number, Boolean],
    default: "",
  },
  // 标签大小
  size: {
    type: String,
    default: "default",
    validator: (value) => ["large", "default", "small"].includes(value),
  },
  // 自定义样式类
  customClass: {
    type: String,
    default: "",
  },
  // 标签效果
  effect: {
    type: String,
    default: "light",
    validator: (value) => ["light", "dark", "plain"].includes(value),
  },
  // 是否圆角
  round: {
    type: Boolean,
    default: false,
  },
  // 是否可关闭
  closable: {
    type: Boolean,
    default: false,
  },
  // 默认标签类型（当字典中未找到对应类型时使用）
  defaultType: {
    type: String,
    default: "info",
    validator: (value) =>
      ["success", "warning", "danger", "info", "primary"].includes(value),
  },
  // 默认显示文本（当字典中未找到对应文本时使用）
  defaultText: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["close"]);

const dictStore = useDictStore();
// 字典选项
const dictOptions = ref([]);
// 加载状态
const loading = ref(false);

// 计算显示文本
const displayText = computed(() => {
  if (props.value === null || props.value === undefined || props.value === "") {
    return props.defaultText || "未知";
  }

  // 处理布尔值
  const searchValue =
    typeof props.value === "boolean"
      ? props.value
        ? "1"
        : "0"
      : String(props.value);

  const option = dictOptions.value.find((item) => {
    const itemValue = String(item.value);
    return itemValue === searchValue;
  });

  return option ? option.label : props.defaultText || props.value;
});

// 计算标签类型
const tagType = computed(() => {
  if (props.value === null || props.value === undefined || props.value === "") {
    return props.defaultType;
  }

  // 处理布尔值
  const searchValue =
    typeof props.value === "boolean"
      ? props.value
        ? "1"
        : "0"
      : String(props.value);

  const option = dictOptions.value.find((item) => {
    const itemValue = String(item.value);
    return itemValue === searchValue;
  });

  // 如果字典项中有type字段，使用字典中的类型，否则使用默认类型
  if (option && option.type) {
    return option.type;
  }

  // 如果没有找到对应的字典项，根据值返回默认类型
  if (!option) {
    return props.defaultType;
  }

  // 根据状态值推断类型（向后兼容）
  if (searchValue === "1" || searchValue === "true" || searchValue === "启用") {
    return "success";
  } else if (
    searchValue === "0" ||
    searchValue === "false" ||
    searchValue === "禁用"
  ) {
    return "danger";
  }

  return props.defaultType;
});

// 加载字典数据
const loadDictData = async () => {
  if (!props.dictType) return;

  loading.value = true;
  try {
    const response = await dictStore.fetchDictDataByType({ code: props.dictType });

    if (response) {
      dictOptions.value = response.map((item) => ({
        value: item.value,
        label: item.label,
        type: item.type || null, // 支持字典项中定义标签类型
      }));
    } else {
      dictOptions.value = [];
    }
  } catch (error) {
    // 加载字典数据失败处理
    dictOptions.value = [];
  } finally {
    loading.value = false;
  }
};

// 重新加载数据
const reload = () => {
  dictStore.reloadDictData({ code: props.dictType });
};

// 获取字典选项
const getOptions = () => dictOptions.value;

// 处理关闭事件
const handleClose = () => {
  emit("close");
};

// 暴露方法给父组件
defineExpose({
  reload,
  getOptions,
});

// 监听字典类型变化
watch(
  () => props.dictType,
  () => {
    loadDictData();
  },
  { immediate: true }
);

// 组件挂载时加载数据
onMounted(() => {
  loadDictData();
});
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>